/*
 * Copyright (c) 1997-2012 InfoReach, Inc. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * InfoReach ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with InfoReach.
 *
 * CopyrightVersion 2.0
 *
 */

package com.inforeach.util.string;

/**
 * @author dmytros
 *
 */
public class JavaLikeQuotingUniTransformer implements IStringUniTransformer
{

    boolean isPrintable(char ch)
    {
        return ch >= 0x20 && ch < 0x7f;
    }

    @Override
    public void transform(CharSequence source, StringBuilder target)
    {
        char[] arr = source.toString().toCharArray();
        int f = 0, i;
        for (i = 0; i < arr.length; ++i)
        {
            char ch = arr[i];
            String replacement = null;
            if (!isPrintable(ch))
            {
                switch (ch)
                {
                case '\0': replacement = "\\0"; break;
                case '\b': replacement = "\\b"; break;
                case '\t': replacement = "\\t"; break;
                case '\n': replacement = "\\n"; break;
                case '\f': replacement = "\\f"; break;
                case '\r': replacement = "\\r"; break;
                default  : replacement = "\\u".concat(Integer.toHexString(ch | 0x10000).substring(1)); break;
                }
            }
            else
            {
                switch (ch)
                {
                case '\"': replacement = "\\\""; break;
                case '\'': replacement = "\\\'"; break;
                case '\\': replacement = "\\\\"; break;
                }
            }
            if (replacement != null)
            {
                target.append(arr, f, i - f).append(replacement);
                f = i + 1;
            }
        }
        target.append(arr, f, i - f);
    }

}
